import axios, {
  AxiosInstance,
  AxiosResponse,
  CreateAxiosDefaults,
  InternalAxiosRequestConfig,
  AxiosError,
} from "axios";

//封装 axios 类封装、
class Ajax {
  // 请求实例
  private instance: AxiosInstance; // AxiosInstance 约束实例
  constructor(config: CreateAxiosDefaults) {
    this.instance = axios.create(config); // 创建实例
    // 实例化之后调用拦截方法
    this.beforeRequest();
    this.beforeResponse();
  }
  // 拦截
  private beforeRequest() {
    // 请求拦截
    this.instance.interceptors.request.use(
      (req: InternalAxiosRequestConfig) => {
        // req.headers.Authorization

        return req;
      }
    );
  }

  private beforeResponse() {
    // 响应拦截
    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        return res;
      },
      (err: AxiosError) => {
        // 拦截错误
        console.log(err, 123);
        return err;
      }
    );
  }

  // 请求方法
  post<T>(url: string, data?: T): Promise<AxiosResponse> {
    // promise后台返回的数据
    console.log(data, "request");

    return this.instance({
      method: "post",
      data,
      url,
    });
  }

  get<T>(url: string, params?: T): Promise<AxiosResponse> {
    // promise后台返回的数据
    return this.instance({
      method: "get",
      params, // 拼装在路径后面 url?键=值&键=值
      url,
    });
  }
}

export default Ajax;
